<style></style>
<template>
  <!-- 头部搜索 -->
  <div style="margin-bottom: 10px;">
    <span style="margin-right: 10px;">用户姓名:</span>
    <el-input v-model="searchText" style="width: 240px;margin-right: 10px;" placeholder="请输入用户姓名" />
    <el-button :icon="Search" type="primary" @click="btnSearch()" plain>搜索</el-button>
    <!-- 打开添加弹窗 -->
    <el-button type="success" @click="Add()" plain>
      <el-icon>
        <Plus />
      </el-icon>添加新用户
    </el-button>
  </div>

  <!-- 表格 -->
  <!-- 设置表格中的语言配置为中文 -->
  <el-config-provider :locale="zhCn">
    <el-table :data="tableData" row-key="Sysid" style="width: 100%;" @selection-change="handleSelectionChange">
      <el-table-column label="编号" prop="Sysid" align="center" />
      <el-table-column label="用户名" prop="Sysname" align="center" />
      <el-table-column label="用户姓名" prop="Sysrealname" align="center" />
      <el-table-column label="性别" prop="Syssex" align="center" />
      <el-table-column label="用户照片" prop="Sysimg" align="center">
        <template #default="scope">
          <el-image style="width: 70px; height: 70px" :src="scope.row.Sysimg" />
        </template>
      </el-table-column>
      <el-table-column label="身份证号码" prop="Sysidcard" :show-overflow-tooltip='true' align="center" />
      <el-table-column label="用户角色" prop="Rolename" align="center" />
      <el-table-column label="联系方式" prop="Telephone" :show-overflow-tooltip='true' align="center" />
      <el-table-column label="用户状态" prop="Sysstate" align="center">
        <template #default="scope">
          <el-tag :type="scope.row.Sysstate ? 'primary' : 'success'">{{ scope.row.Sysstate ? "可用" : "不可用" }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" prop="Createtime" align="center">
        <template #default="scope">
          <span>{{ convertDateTime(scope.row.Createtime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="180" align="center">
        <template #default="scope">
          <el-button type="warning" :icon="Edit" @click="handleEdit(scope.$index, scope.row)" plain>编辑</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <div class="demo-pagination-block" style="margin-top: 10px;">
      <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[5, 10, 20, 50, 100]"
        :small="small" :disabled="disabled" :background="background" layout="total, sizes, prev, pager, next, jumper"
        :total="total" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
    </div>
  </el-config-provider>
  <!-- 添加/编辑Form -->
  <el-config-provider :locale="zhCn">
    <el-dialog v-model="dialogFormVisible" :title="dialogTitle" width="500" :destroy-on-close="true"
      :before-close="clearform">
      <el-form :model="form" :rules="rules" ref="ruleFormRef" status-icon :label-position="labelPosition"
        class="demo-form-inline">
        <!-- 业主姓名-->
        <el-form-item label="用户名" :label-width="formLabelWidth" prop="Sysname">
          <el-input v-model="form.Sysname" placeholder="请输入业主姓名" autocomplete="off" />
        </el-form-item>

        <!-- 业主登录名 -->
        <el-form-item label="用户姓名" :label-width="formLabelWidth" prop="Sysrealname">
          <el-input v-model="form.Sysrealname" :readonly="rea" placeholder="请输入用户姓名" autocomplete="off" />
        </el-form-item>

        <!-- 住址 -->
        <el-form-item label="用户角色" :label-width="formLabelWidth" prop="Roleid">
          <el-select v-model="form.Roleid" class="m-2" clearable placeholder="用户角色" style="width: 260px">
            <el-option v-for="item in RoleInfo" :key="item.Roleid" :label="item.Rolename" :value="item.Roleid" />
          </el-select>
        </el-form-item>

        <!-- 头像-->
        <el-form-item label="用户头像" :label-width="formLabelWidth" prop="Sysimg">
          <el-upload action="#" list-type="picture-card" :auto-upload="false" @change="changehaner">
            <el-icon>
              <Plus />
            </el-icon>
            <template #file="{ file }" v-if="showActions">
              <div>
                <img class="el-upload-list__item-thumbnail" :src="file.url" alt="" />
                <span class="el-upload-list__item-actions">
                  <span class="el-upload-list__item-preview" @click="handlePictureCardPreview(file)">
                    <el-icon><zoom-in /></el-icon>
                  </span>
                  <span v-if="!disableds" class="el-upload-list__item-delete" @click="handleDownload(file)">
                    <el-icon>
                      <Download />
                    </el-icon>
                  </span>
                  <span v-if="!disableds" class="el-upload-list__item-delete" @click="handleRemove(file)">
                    <el-icon>
                      <Delete />
                    </el-icon>
                  </span>
                </span>
              </div>
            </template>
          </el-upload>
          <el-dialog v-model="dialogVisible">
            <img w-full :src="dialogImageUrl" alt="Preview Image" style="width: 100%; height: 100%;" />
          </el-dialog>
        </el-form-item>

        <!-- 性别-->
        <el-form-item label="用户性别" :label-width="formLabelWidth" prop="Syssex">
          <el-radio-group v-model="form.Syssex">
            <el-radio value="男" size="large" border>男</el-radio>
            <el-radio value="女" size="large" border>女</el-radio>
          </el-radio-group>
        </el-form-item>

        <!-- 联系方式-->
        <el-form-item label="联系方式" :label-width="formLabelWidth" prop="Telephone">
          <el-input v-model="form.Telephone" placeholder="请输入联系方式" autocomplete="off" />
        </el-form-item>

        <!-- 出生日期 -->
        <el-form-item label="出生日期" :label-width="formLabelWidth" prop="Birthday">
          <el-date-picker v-model="form.Birthday" type="datetime" placeholder="请选择出生日期" style="width: 260px" />
        </el-form-item>

        <!-- 身份证号 -->
        <el-form-item label="身份证号" :label-width="formLabelWidth" prop="Sysidcard">
          <el-input v-model="form.Sysidcard" :readonly="rea" placeholder="请输入身份证号" autocomplete="off" />
        </el-form-item>

        <!-- 状态-->
        <el-form-item label="用户状态" :label-width="formLabelWidth" prop="Sysstate">
          <el-switch v-model="form.Sysstate" class="ml-2" inline-prompt active-text="可用" inactive-text="不可用" />
        </el-form-item>

      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="clearform">取消</el-button>
          <el-button type="primary" @click="btnSave(ruleFormRef)">
            保存
          </el-button>
        </span>
      </template>
    </el-dialog>
  </el-config-provider>
</template>

<script setup>
import { ref, onMounted, reactive } from 'vue'
import axios from 'axios'
import zhCn from 'element-plus/dist/locale/zh-cn.mjs'
import { ElMessage, ElMessageBox, FormRules, FormInstance } from 'element-plus'
import { ElTable } from 'element-plus'
import { Search, Plus, Edit, Delete } from '@element-plus/icons-vue'
import * as qiniu from 'qiniu-js';

//存储表格数据信息
let tableData = ref([]);

//搜索信息
var searchText = ref("");

//控制打开/关闭模态框
const dialogFormVisible = ref(false)
//表单输入框前标题宽度
const formLabelWidth = '100px'
//弹出层标题
var dialogTitle = ref("")

onMounted(() => {
  bindData(currentPage.value, pageSize.value, searchText.value);
  bindAddSelect()
})

//存储表单数据
var form = ref({
  Sysid: 0,
  Roleid: null,
  Sysname: '',
  Sysrealname: '',
  Syssex: '男',
  Sysimg: '',
  Telephone: '',
  Birthday: '',
  Sysidcard: '',
  Sysstate: true,
  Createtime: '2024-03-13T08:52:22.985Z',
  Isdelete: true,
  Syspassword: '123456'
})

//添加业主信息
function Add() {
  dialogFormVisible.value = true;
  dialogTitle.value = "添加管理人员";
}

//编辑业主信息
const handleEdit = (index, row) => {
  dialogFormVisible.value = true;
  dialogTitle.value = "编辑管理人员";
  form.value = row;
  form.value.Syspassword = '123456'
}

//保存
function btnSave(formEl) {
  if (!formEl) return
  formEl.validate((valid) => {
    if (valid) {
      axios({
        method: form.value.Sysid > 0 ? 'put' : 'post',
        data: form.value,
        url: 'https://localhost:7090/api/SystemInfo',
        headers: { 'Content-Type': 'application/json' }
      }).then((res) => {
        if (res) {
          ElMessage({
            message: '保存成功',
            type: 'success',
          })
          clearform()
          bindData(currentPage.value, pageSize.value, searchText.value);
        } else {
          ElMessage({
            message: '保存失败',
            type: 'error',
          })
        }
      }).catch((err) => {
        ElMessage({
          message: err,//"网络异常，请联系管理员!!!"
          type: 'error',
        })
      })
    } else {
      return false
    }
  })
}

// 身份证号校验
const checkIdNum = (rule, value, callback) => {
  if (!value) {
    return callback(new Error('身份证不能为空'))
  }
  if (!/(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/.test(value)) {
    callback(new Error('请输入正确的二代身份证号码'))
  } else {
    callback()
  }
}

//验证
const ruleFormRef = ref();
//添加表单校验
const rules = reactive({
  Sysname: [{
    required: true,//必填
    message: '用户名',
    trigger: 'change'
  }],
  Sysrealname: [{
    required: true,//必填
    message: '请输入用户姓名',
    trigger: 'change'
  }],
  Roleid: [{
    required: true,//必填
    message: '请选择角色',
    trigger: 'change'
  }],
  Telephone: [{
    required: true,
    message: "手机号不能为空",
    trigger: "change"
  }, {
    pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
    message: "请输入正确的手机号码",
    trigger: "change"
  }],
  Birthday: [{
    required: true,
    message: "出生日期不能为空",
    trigger: "change"
  }],
  Sysidcard: [{
    required: true,
    message: "身份证号不能为空",
    trigger: "change"
  },
  {
    validator: checkIdNum,
    trigger: 'change'
  }]
})

//绑定数据表格
function bindData(page, limit, sysrealname) {
  axios.get(`https://localhost:7090/api/SystemInfo?page=${page}&limit=${limit}&sysrealname=${sysrealname}`)
    .then(function (response) {
      tableData.value = response.data.data;
      total.value = response.data.total;
    })
}

const RoleInfo = ref([]);
//绑定添加下拉框
function bindAddSelect() {
  axios.get(`https://localhost:7090/api/RoleInfo/getRoleInfo`)
    .then(function (response) {
      RoleInfo.value = response.data;
    }
    )
}

//模糊查询
function btnSearch() {
  bindData(currentPage.value, pageSize.value, searchText.value);
}

//分页
const currentPage = ref(1)//当前页数
const small = ref(false)
const background = ref(true)
const disabled = ref(false)
const pageSize = ref(5)//每页条数
const total = ref(0)//总数据量

//切换每页条数
const handleSizeChange = (val) => {
  bindData(currentPage.value, pageSize.value, searchText.value);
}

//切换页数
const handleCurrentChange = (val) => {
  bindData(currentPage.value, pageSize.value, searchText.value);
}

//上传图片到七牛云
function changehaner(e) {
  console.log(e);
  //console.log(fileinfo)
  // const file = e.target.files[0];
  const file = e.raw;
  console.log("file");
  console.log(file);
  //const file =fileinfo;

  const key = getNowDate() + file.name;
  //获取七牛云token
  axios.get('https://localhost:7090/api/UploadImgToQINiuYun').then((res) => {
    var token = res.data.token;
    const putExtra = {
      fname: '',
      params: {},
      mimeType: ['image/png', 'image/jpeg', 'image/jpg'],//要求上传的格式
    };
    const config = {
      useCdnDomain: true, //使用cdn加速
    };
    const observable = qiniu.upload(file, key, token, putExtra, config);
    console.log(observable);
    observable.subscribe({
      next: (result) => {
        // 主要用来展示进度
        console.warn(result);
      },
      error: (error) => {
        console.log(error)
      },
      complete: (res) => {
        console.log(res.key);
        // 生成图片路径
        const domain = 'http://sa5wewjw9.hd-bkt.clouddn.com'; // 替换为您的七牛云域名
        const imageURL = `${domain}/${res.key}`;
        console.log(imageURL);
        form.value.Sysimg = imageURL;
      },
    });
  })
}

//用于清空表单
function clearform() {
  dialogFormVisible.value = false;
  form.value = {
    Sysid: 0,
    Roleid: null,
    Sysname: '',
    Sysrealname: '',
    Syssex: '男',
    Sysimg: '',
    Telephone: '',
    Birthday: '',
    Sysidcard: '',
    Sysstate: true,
    Createtime: '2024-03-13T08:52:22.985Z',
    Isdelete: true,
    Syspassword: ''
  };
}


//获取当前时间，用于拼接上传图片的名称
function getNowDate() {
  const now = new Date();
  const year = now.getFullYear();
  const month = ('0' + (now.getMonth() + 1)).slice(-2);
  const day = ('0' + now.getDate()).slice(-2);
  const hours = ('0' + now.getHours()).slice(-2);
  const minutes = ('0' + now.getMinutes()).slice(-2);
  const seconds = ('0' + now.getSeconds()).slice(-2);
  return `${year}${month}${day}${hours}${minutes}${seconds}`;
}

//转换日期时间
function convertDateTime(dateStr) {
  var datetimeObj = new Date(dateStr);
  var year = datetimeObj.getFullYear();
  var month = ("0" + (datetimeObj.getMonth() + 1)).slice(-2);
  var day = ("0" + datetimeObj.getDate()).slice(-2);
  var formattedDate = year + "-" + month + "-" + day;
  return formattedDate;
}
</script>